package com.gujianjian.testjwt.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.gujianjian.testjwt.aspect.PassToken;
import com.gujianjian.testjwt.service.AccountService;
import com.gujianjian.testjwt.utils.JwtUtils;
import com.gujianjian.testjwt.vo.AccountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;

/**
 * @author joy
 * @email 413735709@qq.com
 * @date 2021/12/12 9:07 下午
 */
@RestController
@RequestMapping
public class TestController {

    @Autowired
    private AccountService accountService;
    /**
     * 用户登录：获取账号密码并登录，如果不对就报错，对了就返回用户的登录信息
     * 同时生成jwt返回给用户
     *
     * @return
     */
    @PassToken
    @GetMapping(value = "/login")
    public AccountVO login(String userName, String password) {
        // 这里模拟数据库查询 用户名guxiaojian,密码123456
        // 如果登录失败抛出异常loginFailed
        accountService.login(userName,password);

        //如果登录成功，则返回账号信息
        AccountVO account = accountService.getAccountByUserName(userName);

        //创建token
        String jwtToken = JwtUtils.createToken(
                // 这里将userId作为签发对象
                account.getUserId(),
                account.getNickname(),
                account.getUsername());

        //将token放到accountVO
        account.setToken(jwtToken);

        return account;

    }

    @GetMapping(value = "/getUserInfo")
    public String getUserInfo(HttpServletRequest req) {
        //之前在拦截器里设置好的名字现在可以取出来直接用了
        String userName = (String) req.getAttribute("username");
        String realName = (String) req.getAttribute("realname");
        return userName+"_"+realName;
    }


}
